
<?php
    /**
    *Definig index page of the system
    */
    function __autoload($class_name) 
    {
        include $class_name . '.php';
    }
    $page = new page('school_rs');
    
    $content='';    
    if(isset($_SESSION['user'])  )
    {
        try
        {
            $_SESSION['user']->validate();
        }catch(Exception $e)
        {
            header('Location: login.php');       
        }
        if(isset($_GET['action']) && $_GET['action'] == 'logout')
        {
            unset($_SESSION['user']);
            header('Location: index.php');       
            exit();
        }else
            $content .= 'vitejte '. $_SESSION['user']->__get('name') . '</br>';
    }else
    {
        //TODO: stranka pro hosta        
        $content .= 'vitejte na strankach. Jste neprihlaseny uzivatel!
         <br />
        prihlaste se!
        <br />';  
    }
    $page_num = 1;
    if(isset($_GET['page']))
    {
        try
        {
            checker::checkInt( $_GET['page']);
            $page_num = (int)$_GET['page'];
        }
        catch(UnexpectedValueException $e)
        {
        }
      
    }
   
    $section = '';
    $section_to_select = '';
    if(isset($_GET['section']))
    {
        try
        {
            checker::checkInt( $_GET['section']);
            $section = (int)$_GET['section'];
            $section_to_select = ' AND id_section = '.$section;
        }catch(UnexpectedValueException $e)
        {
        }
        
        
    }  
    
    $query = 'SELECT COUNT(id) AS row_count FROM articles WHERE state = true'.$section_to_select;
    $conn = new dbConnection();
    $sql_result = $conn->db_query($query);
    $row = mysql_fetch_array($sql_result,MYSQL_ASSOC);
    $row_count = (int)$row['row_count'];
    $query = sprintf("SELECT id, 
    id_author, 
    id_section, 
    date, 
    counter,
    priority, 
    header, 
    anotation,
    pending
    FROM articles WHERE state = true %s LIMIT %d, %d ",
            $section_to_select,
            (($page_num-1)*paging::$perPage),
            paging::$perPage);    
    $sql_result = $conn->db_query($query); 
    //TODO error u query
    if (!$sql_result) 
    {
        die('Invalid query: ' . mysql_error());
    }
           
    while($row = mysql_fetch_array($sql_result,MYSQL_ASSOC))
    {        
        $article=new article($row['id'],
        $row['id_author'],
        $row['id_section'],
        $row['date'],
        $row['counter'],
        $row['header'],
        $row['anotation'],
        null,
        $row['pending']);
        $content .= $article;
    }      
    $paging = new paging( $row_count, $page_num, paging::$perPage);
    $content .= $paging;
    echo $page($content);
        
?>
